
module.exports = (app) => {
    const express = require("express");
    const route = express.Router();
    const jwt = require('jsonwebtoken');
    const assert = require('http-assert')
    //token验证中间件
    const verifyToken = require('../../middleware/verifyToken')(app)
    //用户数据模型
    const adminUser = require('../../model/AdminUser')
    //创建集合加创建数据
    route.post("/", async (req, res) => {
        const category = require(`../../model/${req.Model}`);
        const module = await category.create(req.body);
        res.send(module);
    });
    //获取分类列表
    route.get("/",  async (req, res) => {
        const queryOption = {};
        //条件查找
        if (req.Model === "Category") queryOption.populate = "parent";
        if (req.Model === "Article") queryOption.populate = "types";

        const category = require(`../../model/${req.Model}`);

        const item = await category.find().setOptions(queryOption).limit(10);
        res.send(item || []);
    });

    //获取被编辑数据的详情
    route.get("/:id", async (req, res) => {
        const category = require(`../../model/${req.Model}`);

        const model = await category.findById(req.params.id);

        res.send(model);
    });

    //更新分类数据
    route.put("/:id", async (req, res) => {
        const category = require(`../../model/${req.Model}`);
        const result = await category.findByIdAndUpdate(req.params.id, req.body);
        res.send(result);
    });

    //删除分类数据
    route.delete("/:id", async (req, res) => {
        const category = require(`../../model/${req.Model}`);
        const result = await category.findByIdAndDelete(req.params.id);
        res.send(result);
    });
    //入口
    app.use(
        "/rest/:resouce",verifyToken,
        async (req, res, next) => {
            //赋值到所有请求体上  为仓库名category
            req.Model = require("inflection").classify(req.params.resouce);
            next();
        },
        route
    );
    //处理图片上传
    const path = require("path");
    const multer = require("multer");
    const upload = multer({dest: path.resolve(__dirname + "../../../uploads")});

    app.use("/upload", upload.single("file"), (req, res) => {
        const file = req.file;
        file.url = `http://localhost:8090/uploads/${file.filename}`;
        res.send(file);
    });
    //文章富文本编辑器上传图片
    const article = multer({
        dest: path.resolve(__dirname + "../../../article"),
    });
    app.use(
        "/article",
        article.single("wangeditor-uploaded-image"),
        (req, res) => {
            const file = req.file;
            file.url = `http://localhost:8090/uploads/${file.filename}`;
            res.send({
                errno: 0, // 注意：值是数字，不能是字符串
                data: {
                    url: file.url, // 图片 src ，必须
                },
            });
        }
    );

    //登录接口
    app.use('/login', async (req, res) => {
        const {username, password} = req.body

        //查找用户
        const user = await adminUser.findOne({username}).select('+password')
        assert(user,422,'用户不存在')

        //验证密码
        const isTrue = require('bcryptjs').compareSync(password, user.password)
        assert(isTrue,422,'密码错误')


        //返回token

        const token = jwt.sign({id: user._id}, app.get('secret'),{expiresIn:'6h'})
        res.send({
            token,
            message: '登录成功'
        })
    })
    //验证token接口
    app.use('/verifyToken',verifyToken, async (req,res) => {
        res.send({
            isLogin:'true',
            message:'登录成功'
        })
    })

    //错误处理函数
    app.use(async (err,req,res,next)=>{

        res.status(err.statusCode || 500).send({
            message:err.message
        })
    })
};
